from collections import Counter
from .node import _get_attr_

__all__ = ['cal_average_dgree', 'get_attr_distribution', 'cal_dgree_distribution']

def cal_average_dgree(graph):
    """
    计算网络中的平均度

    :param graph: 图对象
    :return: float, 平均度
    """

    # 计算度之和
    degree_sum = 2 * len(graph['edges'])

    # 计算节点数
    vertix_num = len(graph['vertices'])

    # 计算平均度
    return degree_sum / vertix_num


def get_attr_distribution(graph, feature):
    """
    计算图中某个属性的分布。

    :param graph: 图对象
    :param feature: 需统计的属性
    :return: 若属性存在，返回Collection.Counter；若不存在，打印提示。
    """

    nodes = graph["vertices"]
    if feature in nodes[0].keys():
        distrib = Counter([_get_attr_(node, feature) for node in nodes])
        return distrib
    else:
        print(f"The graph has not attr {feature}")

# //FIXME
def cal_dgree_distribution(graph):
    """
    计算网络的度分布

    :param graph: 图对象
    :return:
    """

    ind = [edge[0] for edge in graph['edges']]
    outd = [edge[1] for edge in graph['edges']]
    deg_vertex = Counter(ind + outd)  # 计算各顶点度数
    degree_stat = Counter(deg_vertex.values())
    x = sorted(list(degree_stat.keys()))
    p0 = len(graph['vertices']) - len(deg_vertex)
    p = [degree_stat[key] for key in x]

    return ['0'] + x, [p0] + p
